package com.aiatomic.couting.widgets;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import com.aiatomic.couting.util.HttpUtils;
import com.aiatomic.couting.util.ImageUtils;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.widget.ImageView;

class DownloadImageTask extends AsyncTask<String, Void, Drawable> {
	private ImageView mImageView;
	private int resId;

	public DownloadImageTask(ImageView mImageView, int resId) {
		super();
		this.mImageView = mImageView;
		this.resId = resId;
	}

	public static Bitmap drawableToBitmap(Drawable drawable) {

		Bitmap bitmap = Bitmap.createBitmap(

				drawable.getIntrinsicWidth(),

				drawable.getIntrinsicHeight(),

				drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888

						: Bitmap.Config.RGB_565);

		Canvas canvas = new Canvas(bitmap);

		drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());

		drawable.draw(canvas);

		return bitmap;

	}

	protected Drawable doInBackground(String... params) {
		String url = params[0];
		Drawable drawable = null;
		File cacheDir = new File(mImageView.getContext().getExternalCacheDir(),
				mImageView.getContext().getString(resId));
		File cacheFile = new File(cacheDir, HttpUtils.md5(url));
		if (cacheFile.exists()) {
			drawable=Drawable.createFromPath(cacheFile.getAbsolutePath());
		} else {
			drawable = ImageUtils.getInstance().loadImageFromNetwork(url);
			if (drawable != null) {
				cacheDir.mkdir();
				FileOutputStream out;
				try {
					out = new FileOutputStream(cacheFile);
					Bitmap bm = drawableToBitmap(drawable);
					bm.compress(Bitmap.CompressFormat.PNG, 90, out);
					out.flush();
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		}
		return drawable;
	}

	protected void onPostExecute(Drawable result) {
		mImageView.setImageDrawable(result);
	}

}